// app/lib/circuit_breaker.js
'use strict';

class CircuitBreaker {
  constructor(config) {
    this.states = new Map();
    this.config = config;
  }

  trigger(service) {
    const state = this.states.get(service) || { failures:0, successes:0 };
    state.failures++;
    if(state.failures >= this.config[service].failureThreshold) {
      state.open = true;
      state.openedAt = Date.now();
    }
    this.states.set(service, state);
  }

  isOpen(service) {
    const state = this.states.get(service);
    if(!state?.open) return false;
    
    if(Date.now() - state.openedAt > this.config[service].timeout) {
      state.open = false;
      state.failures = 0;
      return false;
    }
    return true;
  }
}

module.exports = CircuitBreaker;